package com.xiaoyi.springboot.service.impl;

import com.xiaoyi.springboot.entity.DriftingBottle;
import com.xiaoyi.springboot.entity.DriftingBottleFished;
import com.xiaoyi.springboot.mapper.DriftingBottleMapper;
import com.xiaoyi.springboot.service.DriftingBottleFishedService;
import com.xiaoyi.springboot.service.DriftingBottleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoyi
 * @since 2021-10-10
 */
@Service
public class DriftingBottleServiceImpl extends ServiceImpl<DriftingBottleMapper, DriftingBottle> implements DriftingBottleService {

    @Autowired
    private  DriftingBottleMapper driftingBottleMapper;
    private static final int LAST_LIMIT = 100;
    private static final  Random random = new Random();
    @Autowired
    private DriftingBottleFishedService  driftingBottleFishedService;
    @Override
    public DriftingBottle takeDriftingBottle(String userNameByToken) {
        // 从数据库里面随机获取一条数据，数据里面只查询前100条数据
        // 从前100条数据里面，随机获取一条数据，然后返回
        List<Long> ids = driftingBottleMapper.getLastLimit(LAST_LIMIT,userNameByToken);
        if (CollectionUtils.isEmpty(ids)){
            return null;
        }
        // 拿到
        int size = ids.size();
        int index = random.nextInt(size);
        // 拿到数据的最终id
        Long id = ids.get(index);
        DriftingBottle driftingBottle = driftingBottleMapper.takeDriftingBottleById(id,userNameByToken);
        insertToInTaked(driftingBottle,userNameByToken);
        return driftingBottle;
    }
    /*
     *
     * @author xiaoyi
     * @date 2021/10/10 19:34
     * @param driftingBottle
     * @param userNameByToken
     * @return void
     * @version v1.0
     */
    @Async
    public void insertToInTaked(DriftingBottle driftingBottle, String userName) {
        // 保存已读
        DriftingBottleFished driftingBottleFished = new DriftingBottleFished();
        driftingBottleFished.setCreateTime(new Date());
        driftingBottleFished.setCreateBy(userName);
        driftingBottleFished.setUpdateBy(userName);
        driftingBottleFished.setUpdateTime(new Date());
        driftingBottleFished.setState(1);
        driftingBottleFished.setUserAccount(userName);
        driftingBottleFished.setDriftingBottleId(driftingBottle.getId());
        driftingBottleFishedService.save(driftingBottleFished);
    }
}
